require 'classes'

class("Log", Object)

Log.logs = {}

Log.warning = "Warning:"
Log.error   = "ERROR:"
Log.critical = "*** CRITICAL:"

-- Default settings
Log.destination = io.stdout
Log.name = "(unnamed log)"

Log.loggingEnabled = true

function Log:enableLogging(mode)
    Log.loggingEnabled = mode
end

function Log:getLog(name)
    local l = Log.logs[name]
    if l then
        return l
    else
        return Log:create(name, Log.destination)
    end
end

function Log:_construct(...)
    local name, destination = ...
    if name then self:setName(name) end
    if destination then self:setDestination(destination) end
    Object._construct(self)
    self:print("Log started at " .. os.date())
end

function Log:setName(name)
    self.name = name
    Log.logs[name] = self
end

function Log:setDestination(destination)
    self.destination = destination
    -- this opens the session, so print a 'hello world'
    --printLogHeader()
end

function Log:printLogHeader()
    destination = self.destination
    destination:write("--------\n")
    destination:write(os.date() .. "\n")
    destination:write("--------\n")
end

function Log:print(str, severity)
    
    if Log.loggingEnabled == false then
        return
    end

    local d = self.destination
    
    d:write(self.name .. ": ")

    if (severity) then
        d:write(severity .. " ")
    end
    
    d:write(str .. "\n")
end
